// 过滤富文本标签
export function filterHTMLTag(text: string): string {
  if (!text) return ''
  text = text.replace(/<\/?[^>]*>/g, '') //去除HTML Tag
  text = text.replace(/[|]*\n/, '') //去除行尾空格
  text = text.replace(/&npsp;/gi, '') //去掉npsp
  // 移除空格
  text = text.replace(/&nbsp;/gi, '')
  text = text.replace(/['"\\/\b\f\n\r\t]/g, '') // 去除转义字符

  return text
}

export function transferSrcToDataAttribute(
  htmlStr: string,
  isRemoveOriginalSrc = true
) {
  const container = document.createElement('p')
  container.innerHTML = htmlStr

  Array.from(container.querySelectorAll('img')).forEach((item) => {
    const src = item.getAttribute('src')
    item.setAttribute('data-src', src || '')

    if (isRemoveOriginalSrc) {
      item.removeAttribute('src')
    }
  })

  return container.innerHTML.toString()
}

//获取转换后的html
export function getTransferSrcToDataAttribute(
  htmlStr: string,
  isRemoveOriginalSrc = true
) {
  const container = document.createElement('p')
  container.innerHTML = htmlStr

  Array.from(container.querySelectorAll('img')).forEach((item) => {
    const src = item.getAttribute('data-src')
    item.setAttribute('src', src || '')

    if (isRemoveOriginalSrc) {
      item.removeAttribute('data-src')
    }
  })

  return container.innerHTML.toString()
}

export function transferDataAttributeToSrc(htmlStr: string) {
  const container = document.createElement('p')
  container.innerHTML = htmlStr

  Array.from(container.querySelectorAll('img')).forEach((item) => {
    const dataSrc = item.getAttribute('data-src') || ''

    if (!dataSrc) return
    item.setAttribute('src', dataSrc)
  })

  return container.innerHTML.toString()
}
